package com.ndp.fb.creative.fetchdata.dao.mongodb;

import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by evan on 2015/3/5.
 */
@Component
public class MongodbUtils {

    @Autowired
    private DB mongoDBClient;

    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 根据24小时分表查询统计数据，(改于2015-03-30）
     * startTime ：20150330160000
     * endTime ：20150331155000
     */
    public List<DBObject> searchEndTimeData(List<Long> ids,String tableName, String startTime,String endTime,String columnName) throws Exception {
        List<DBObject> endList = new ArrayList<>();
        Long[] longIds = new Long[ids.size()];
        Object[] obj = ids.toArray();
        for (int i = 0; i < obj.length; i++) {
            longIds[i] =Long.parseLong(obj[i].toString());
        }
        //减去10分钟
//        Date  endDate = DateFormatUtil.parseDate(endTime,new SimpleDateFormat("yyyyMMddHHmmss"));
//        endTime = DateUtil.getDate(endDate, Calendar.MINUTE, -10, "yyyyMMddHHmmss");
        String tempTableName = tableName + "_" + endTime;
        logger.info("***************查询end表为***************" + tempTableName);
        DBCursor cursor = mongoDBClient.getCollection(tempTableName).find(new BasicDBObject(columnName,new BasicDBObject("$in",longIds)));
        if(cursor.size() != 0){
            logger.info("查询成功," + tempTableName + "数量为："+ cursor.size());
            for (DBObject dbObject : cursor) {
                endList.add(dbObject);
            }
            return endList;
        } else {
            logger.error("查询失败，开始结束时间：{}_{}", startTime, endTime);
        }
        return endList;
    }
    //calculate
    public List<DBObject> calculate(Long[] longIds,List<DBObject> startList,List<DBObject> endList,String columnName){
        Map<Long, DBObject> adGroupMap = new HashMap<>(longIds.length);
        List<DBObject> result = new ArrayList<DBObject>();
        if(startList.size() == 0 && endList.size() == 0){
            return result;
        }
        for (DBObject endDbObject : endList) {
            Long endCId = Long.valueOf(endDbObject.get(columnName).toString());
            if(startList.size() != 0){
                for(DBObject satrtDbObject : startList){
                    Long startCId = Long.valueOf(satrtDbObject.get(columnName).toString());
                    if(endCId.equals(startCId)){
                        decProperty(satrtDbObject,endDbObject,"spent");
                        decProperty(satrtDbObject,endDbObject,"impressions");
                        decProperty(satrtDbObject,endDbObject,"clicks");
                        decProperty(satrtDbObject,endDbObject,"uniqueImpressions");
                        decProperty(satrtDbObject,endDbObject,"results");
                    }
                }
            }
            adGroupMap.put(endCId, endDbObject);
        }
        //cost
        for (Long aLong : adGroupMap.keySet()) {
            DBObject dbObject = adGroupMap.get(aLong);
            if((Integer) dbObject.get("results") == 0){
                dbObject.put("cost",0);
            }else{
                dbObject.put("cost", (Integer) dbObject.get("spent") / (Integer) dbObject.get("results"));
            }
            result.add(dbObject);
        }
        return result;
    }

    /**
     *  calculate property
     * @param startObj
     * @param endObj
     * @param property
     */
    public void decProperty(DBObject startObj, DBObject endObj, String property) {
        int startCount = (Integer) startObj.get(property);
        int endCount  = (Integer) endObj.get(property);
        endObj.put(property, endCount - startCount);
    }


    /**
     * 判断是否存在表
     * @param tableName
     * @return
     */
    public boolean isExsitTableByName(String tableName){
        return mongoDBClient.collectionExists(tableName);
    }


    public String createTable(String tableName,String shardKey,List<String> indexList,int ttlTime){
        if (this.isExsitTableByName(tableName)) {
            logger.debug("表已经创建，跳过。。。" + tableName);
            return tableName;
        }
        try {
            mongoDBClient.createCollection(tableName, new BasicDBObject());
            logger.debug("分片名称 >>>> " + shardKey);
            logger.debug("新表创建成功" + tableName);
        }catch (Exception e){
            logger.error("创建表失败createDistanceDayMinitSpiltTable"+ tableName +"****"+ e.getMessage(),e);
            return tableName;
        }
        //创建分片
//        BasicDBObject dbObject = new BasicDBObject();
//        dbObject.put("shardCollection", mongoDBClient.getName() + "." + tableName);
//        dbObject.put("key", new BasicDBObject(shardKey, 1));
//        CommandResult commandResult = mongoDBClient.command(dbObject);
//        String errorMessage = commandResult.getErrorMessage();
//        if (null == errorMessage || "".equals(errorMessage)) {
//            logger.error(commandResult.toString());
//        } else {
//            logger.debug("分片成功");
//        }
        //创建索引
        if(indexList != null){
            DBCollection collection = mongoDBClient.getCollection(tableName);
            for(String indexL:indexList){
                if("endDate".equals(indexL)){
                    DBObject obj1 = new BasicDBObject();
                    obj1.put("endDate",1);
                    DBObject obj2 = new BasicDBObject();
                    obj2.put("expireAfterSeconds",ttlTime); // 2fenzhong后删除表中记录  7776000s = 90天
                    collection.createIndex(obj1, obj2);
                }else{
                    collection.createIndex(new BasicDBObject(indexL, 1));
                }
                logger.debug("创建索引成功 >>>> " + indexL);
            }
        }
        return tableName;
    }




}
